#include "mod_list.h"

bool mod_list::add(mod *m){
    if (m->getname() != ""){
        this->list.push_back(*m);
        m->setid(++size);
        return true;
    }
    else{
        return false;
    }
}

void mod_list::insert(mod *m, int seat)
{
    if(seat==0){
        return ;
    }
    if(seat>size){
        vector<mod>::iterator it = this->list.begin()+seat;
        m->setid(seat);
        this->size = seat;
        this->list.insert(it,1,*m);
    }else{
        vector<mod>::iterator it = this->list.begin()+seat;
        this->list.insert(it,1,*m);
        for( int i=seat; it<this->list.end();seat++,it++){
            mod *m_p =  &list.at(seat);
            m_p->setid(i);
        }
    }
}

mod_list *mod_list::foreach(string name)
{
    mod_list *ml=nullptr;
    vector<mod>::iterator it = list.begin();
    for(int i=1;it<list.begin();it++,i++){

        mod *m_p = &list.at(i);
        if(m_p->getname()==name){
            ml->add(m_p);
        }
    }
    return ml;
}

mod_list *mod_list::foreach(long start, long end)
{
    if(start<1||end>this->size){
        return nullptr;
    }
    mod_list *ml=nullptr;
    vector<mod>::iterator it = list.begin()+start;
    for(int i=start;it<list.begin()+end;it++,i++){
        mod *m_p = &list.at(i);
        ml->add(m_p);
    }
    return ml;
}

bool mod_list::remove(long id)
{
    if(id==0){
        return false;
    }else if( id > this->size){
        return false;
    }
    vector<mod>::iterator it   = this->list.begin()+id;
    this->list.erase(it);
    return true;
}

bool mod_list::update(mod *m, int seat)
{
    if(!m->getname().empty()){
        return false;
    }
    vector<mod>::iterator it = this->list.begin()+seat;
    m->setid(seat);
    *it = *m;
    return true;
}

mod *mod_list::find(string name)
{
    mod *m_p=nullptr;
    vector<mod>::iterator it = this->list.begin();
    for(int i=1;it < list.end();it++,i++){
        m_p=&list.at(i);
        if(m_p->getname()==name){
            return m_p;
        }
    }
    return m_p;
}

mod *mod_list::find(long id)
{

    if(id<0){
        return nullptr;
    }
    else if(id>this->size){
        return nullptr;
    }
    mod *m_p=&list.at(id);
    return m_p;
}

mod *mod_list::find(string name, long id)
{
    if(id<0){
        return nullptr;
    }
    else if(id>this->size){
        return nullptr;
    }
    mod *m_p = &list.at(id);
    if(m_p->getname()!=name){
        return nullptr;
    }
    return m_p;
}

